package org.zhadoop.stream.cql.semanticanalyzer;

import java.util.Map;

import org.zhadoop.stream.api.streams.Column;
import org.zhadoop.stream.api.streams.Schema;
import org.zhadoop.stream.cql.exception.SemanticAnalyzerException;
import org.zhadoop.stream.cql.semanticanalyzer.analyzecontext.CreateStreamAnalyzeContext;
import org.zhadoop.stream.cql.semanticanalyzer.parser.context.ColumnNameTypeContext;
import org.zhadoop.stream.cql.semanticanalyzer.parser.context.ColumnNameTypeListContext;
import org.zhadoop.stream.cql.semanticanalyzer.parser.context.KeyValuePropertyContext;
import org.zhadoop.stream.cql.semanticanalyzer.parser.context.ParseContext;
import org.zhadoop.stream.cql.semanticanalyzer.parser.context.StreamPropertiesContext;

import com.google.common.collect.Maps;

/**
 * create stream 语义分析
 * @author zwd
 *
 */
public abstract class CreateStreamAnalyzer extends BaseAnalyzer{

	private CreateStreamAnalyzeContext analyzeContext = null;
	
	public CreateStreamAnalyzer(ParseContext parseContext) throws SemanticAnalyzerException {
		super(parseContext);
	}

	@Override
	protected CreateStreamAnalyzeContext getAnalyzeContext() {
		return analyzeContext;
	}

	@Override
	protected void createAnalyzeContext() {
		analyzeContext = new CreateStreamAnalyzeContext();
	}
	
	/**
	 * 创建schema
	 * @param streamName
	 * @param columns
	 * @return
	 */
	protected Schema createSchema(String streamName,ColumnNameTypeListContext columns){
		Schema schema = new Schema(streamName);
		for(ColumnNameTypeContext column : columns.getColumns()){
			schema.addCol(new Column(column.getColumnName(), column.getColumnType().getWrapperClass()));
		}
		return schema;
	}
	
	/**
	 * 分析流属性
	 * @param streamPropertiesContext
	 * @return
	 */
	protected Map<String,String> analyzeStreamProperties(StreamPropertiesContext streamPropertiesContext){
		if(streamPropertiesContext == null){
			return Maps.newHashMap();
		}
		
		return parseStreamProperties(streamPropertiesContext);
	}

	private Map<String, String> parseStreamProperties(StreamPropertiesContext streamPropertiesContext) {
		Map<String,String> properties = Maps.newHashMap();
		for(KeyValuePropertyContext ctx : streamPropertiesContext.getProperties()){
			String key = ctx.getKey();
			String value = ctx.getValue();
			properties.put(key, value);
		}
		return properties;
	}
}
